package cn.bdqn.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bdqn.bean.User;
import cn.bdqn.service.UserService;
import cn.bdqn.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {

	/**
		 * The doGet method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to get.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
		
	}

	/**
		 * The doPost method of the servlet. <br>
		 *
		 * This method is called when a form has its tag value method equals to post.
		 * 
		 * @param request the request send by the client to the server
		 * @param response the response send by the server to the client
		 * @throws ServletException if an error occurred
		 * @throws IOException if an error occurred
		 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//获取登录页面用户的数入
		String userCode = request.getParameter("username");
		String password = request.getParameter("password");
		UserService userService = new UserServiceImpl();
		User u = new User();
		if(userCode!=null && password!=null){
			u.setUserCode(userCode);
			u.setPassword(password);
			//获取到users所有信息
			User user =  userService.login(u);
			//判断用户名和密码
			if(user.getUserCode()!=null){
				if(user.getUserCode().equals(userCode) && 
						user.getPassword().equals(password)){
					//登录成功
					//将user添加到session中
					request.getSession().setAttribute("user", user);
					//跳转到welcome界面
					response.sendRedirect("jsp/welcome.jsp");
				}else{
					response.sendRedirect("jsp/login.jsp");
				}
			}else{
				response.sendRedirect("jsp/login.jsp");
			}
		
			
			
		}
	}

}
